import Taro from '@tarojs/taro';

export interface ApiResult {
  code: number;
  success: boolean;
  type: string;
  result: any;
}
const interceptor = (chain) => {
  const { requestParams } = chain;
  return chain.proceed(requestParams).then((res) => {
    if (res.data.code === 0) {
      Taro.showToast({ title: res.data.message }).then();
    }
    // 未登录拦截 不优雅
    if (res.statusCode === 401 || res.data.code === 401) {
      Taro.navigateTo({ url: '/pages/login/index' });
    }
    return res;
  });
};

// const Host = process.env.NODE_ENV === 'development' ? 'http://123.60.213.68:8088' : 'http://hebizcw.cn';
let Host ='http://hebizcw.cn:8088'
export const GET = (url: string, data?: any) =>
  new Promise<ApiResult>((resolve) => {
    let response: ApiResult;
    const token = Taro.getStorageSync('access_token');
    Taro.addInterceptor(interceptor);
    Taro.request({
      url: `${Host}${url}`,
      data,
      method: 'GET',
      header: {
        'Content-type': 'application/json', // 默认值
        Authorization: `Bearer ${token}`,
        Platform: 'wmp',
      },
      success(res) {
        response = res.data;
        resolve(response);
      },
    });
  });

export const POST = (url: string, data?: any) =>
  new Promise<ApiResult>((resolve) => {
    let response: ApiResult;
    const token = Taro.getStorageSync('access_token');
    Taro.addInterceptor(interceptor);
    Taro.request({
      url: `${Host}${url}`,
      data,
      method: 'POST',
      header: {
        'Content-type': 'application/json', // 默认值
        Authorization: `Bearer ${token}`,
        Platform: 'wmp',
      },
      success(res) {
        response = res.data;
        resolve(response);
      },
    });
  });

export const PUT = (url: string, data?: any) =>
  new Promise<ApiResult>((resolve) => {
    let response: ApiResult;
    const token = Taro.getStorageSync('access_token');
    Taro.addInterceptor(interceptor);
    Taro.request({
      url: `${Host}${url}`,
      data,
      method: 'PUT',
      header: {
        'Content-type': 'application/json', // 默认值
        Authorization: `Bearer ${token}`,
        Platform: 'wmp',
      },
      success(res) {
        response = res.data;
        resolve(response);
      },
    });
  });

export const DELETE = (url: string, data?: any) =>
  new Promise<ApiResult>((resolve) => {
    let response: ApiResult;
    const token = Taro.getStorageSync('access_token');
    Taro.addInterceptor(interceptor);
    Taro.request({
      url: `${Host}${url}`,
      data,
      method: 'DELETE',
      header: {
        'Content-type': 'application/json', // 默认值
        Authorization: `Bearer ${token}`,
        Platform: 'wmp',
      },
      success(res) {
        response = res.data;
        resolve(response);
      },
    });
  });
